<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Admin_IndexController
 *
 * @author hoquangminh
 */
class Admin_IndexController extends Core_Controller_Action {

    public function init() {
        parent::init();
        $this->_initMenuUrls();
        // load service
        $this->view->assign("services", Core_Util::getAllServices());
        $this->view->assign("materials", Core_Util::getAllMaterials());
        $this->_helper->layout()->setLayout("admin_layout");
    }

    public function indexAction() {
        $sld_img_db = new Core_Model_DbTable_SlidingImages();
        $images = $sld_img_db->getAll();
        $this->view->images = $images;
    }
    
    public function newimageAction() {
        $this->setAjaxCall();
        if ($this->getRequest()->isPost()) {
            $form = new Admin_Form_Newimage();
            $form_data = $this->getRequest()->getPost();
            if ($form->isValid($form_data)) {
                $data = array (
                    'file'          => $this->uploadFile('file'),
                    'caption'       => $form->getValue("caption"),
                    'created_date'  => time()
                );
                
                $sld_img_db = new Core_Model_DbTable_SlidingImages();
                $sld_img_db->insert($data);
            }
        }
        $this->_helper->redirector("index");
    }
    
    public function editimageAction() {
        $this->setAjaxCall();
        
        $image_id = $this->_getParam("imgid");
        if (!empty($image_id)) {
            $caption = $this->_getParam("caption");

            $data = array ('caption' => $caption);
            $sld_img_db = new Core_Model_DbTable_SlidingImages();
            $sld_img_db->update($data, $sld_img_db->getAdapter()->quoteInto("id = (?)", $image_id));
        }
        
        $this->_helper->redirector("index");
    }
    
    public function deleteimageAction() {
        $this->setAjaxCall();
        
        $image_id = $this->_getParam("imgid");
        if (!empty($image_id)) {
            $sld_img_db = new Core_Model_DbTable_SlidingImages();

            $get_cond = $sld_img_db->getAdapter()->quoteInto("id = (?)", $image_id);
            $old_image = $sld_img_db->fetchRow($get_cond);
            $image_name = $old_image->file;
            unlink(UPLOAD_PATH . $image_name);
            $sld_img_db->delete($get_cond);
        }
        
        $this->_helper->redirector("index");
    }

    public function portsAction() {
        $port_db = new Core_Model_DbTable_Ports();

        if ($this->getRequest()->isPost()) {
            $delete_ids = $this->_getParam("delete_ids");
            $port_db->batchDelete($delete_ids);
        }
        
        $this->view->ports = $port_db->getAll();        
    }
    
    public function newportAction() {
        $port_db = new Core_Model_DbTable_Ports();
        $this->view->mode = INSERT_MODE;
        if ($this->isPost()) {
            $form = new Admin_Form_Newport();
            $form_data = $this->getRequest()->getPost();
            if ($form->isValid($form_data)) {
                $port_data = array (
                    'name'        => htmlspecialchars($form->getValue("name")),
                    'description' => $form->getValue("description"),
                    'latitude'    => htmlspecialchars($form->getValue("latitude")),
                    'longitude'   => htmlspecialchars($form->getValue("longitude"))
                );
                $port_db->insert($port_data);
                $this->_helper->redirector("ports");
            } else {
                $this->view->errors = $form->getMessages();
                $this->view->port = (object)$form_data;
            }
        }
    }
    
    public function editportAction() {
        $port_db = new Core_Model_DbTable_Ports();
        $this->view->mode = EDIT_MODE;
        $pid = $this->_getParam("pid");
        if (!empty($pid)) {
            if ($this->isPost()) {
                $form = new Admin_Form_Newport();
                $form_data = $this->getRequest()->getPost();
                if ($form->isValid($form_data)) {
                    $data = array (
                        'name'          => htmlspecialchars($form->getValue("name")),
                        'description'   => $form->getValue("description"),
                        'latitude'      => htmlspecialchars($form->getValue("latitude")),
                        'longitude'     => htmlspecialchars($form->getValue("longitude"))
                    );
                    $port_db->update($data, $port_db->getAdapter()->quoteInto("id = (?)", $pid));
                    $this->_helper->redirector("ports");                                    
                } else {
                    $this->view->port = (object)$form_data;
                    $this->view->errors = $form->getMessages();                    
                    $this->render("newport");
                }
            } else {
                $port_detail = $port_db->getPortDetail($pid);
                if (!empty($port_detail)) {
                    $this->view->port = $port_detail;
                    $this->render("newport");
                } else {
                    $this->_helper->redirector("newport");
                }
            }
        } else {
            $this->_helper->redirector("newport");
        }
    }
    
    public function buoysAction() {
        $buoy_db = new Core_Model_DbTable_Buoys();
        $this->view->buoys = $buoy_db->getAll();
    }
    
    public function newbuoyAction() {
        $this->view->mode = INSERT_MODE;
        if ($this->getRequest()->isPost()) {
            $form = new Admin_Form_Newbuoy();
            $form_data = $this->getRequest()->getPost();
            if ($form->isValid($form_data)) {
                $buoy_db = new Core_Model_DbTable_Buoys();
                $data = array (
                    'name' => $this->_getParam("name"),
                    'port' => $this->_getParam("port")
                );
                $buoy_db->insert($data);
                $this->_helper->redirector("buoys");
            } else {
                $this->view->buoy = (object)$form_data;
                $this->view->errors = $form->getMessages();
                $port_db = new Core_Model_DbTable_Ports();
                $this->view->ports = $port_db->getAll();                
            }
        } else {
            $port_db = new Core_Model_DbTable_Ports();
            $this->view->ports = $port_db->getAll();
        }
    }
    
    public function editbuoyAction() {
        $this->view->mode = EDIT_MODE;
        $bid = $this->_getParam("bid");
        $need_redirect = false;
        if (!empty($bid)) {
            $buoy_db = new Core_Model_DbTable_Buoys();
            if ($this->getRequest()->isPost()) {
                $form = new Admin_Form_Newbuoy();
                $form_data = $this->getRequest()->getPost();
                if ($form->isValid($form_data)) {
                    $data = array (
                        'name' => htmlspecialchars($form->getValue("name")),
                        'port' => $form->getValue("port")
                    );
                    $buoy_db->update($data, $buoy_db->getAdapter()->quoteInto("id = (?)", $bid));
                    $need_redirect = true;
                } else {
                    $this->view->buoy = (object)$form_data;
                    $this->view->errors = $form->getMessages();
                    $port_db = new Core_Model_DbTable_Ports();
                    $this->view->ports = $port_db->getAll();
                    $this->render("newbuoy");
                }
            } else {
                $buoy = $buoy_db->getDetail($bid);
                if (!empty($buoy)) {
                    $this->view->buoy = $buoy;
                    $port_db = new Core_Model_DbTable_Ports();
                    $this->view->ports = $port_db->getAll();
                    $this->render("newbuoy");
                } else {
                    $need_redirect = true;
                }                
            }
        } else {
            $need_redirect = true;
        }
        
        if ($need_redirect) {
            $this->_helper->redirector("buoys");
        }
    }
    
    public function usersAction() {
        $user_db = new Core_Model_DbTable_Users();
        
        if ($this->getRequest()->isPost()) {
            $delete_ids = $this->_getParam("delete_ids");
            $user_db->batchDelete($delete_ids);
        }
        
        $search_name = $this->_getParam("search_name", '');
        $this->view->search_name = $search_name;
        
        $paginator_adapter = $user_db->getPaginatorAdapter($search_name);
        $paginator = new Zend_Paginator($paginator_adapter);
        $page = $this->_getParam("page", 0);
        $paginator->setCurrentPageNumber($page);
        $this->view->paginator = $paginator;
    }
    
    public function newuserAction() {
        $this->view->mode = INSERT_MODE;
        if ($this->getRequest()->isPost()) {
            $form = new Admin_Form_Newuser();
            $form_data = $this->getRequest()->getPost();
            $errors = array();
            if ($form->isValid($form_data)) {
                $data = array (
                    'username' => $form->getValue("username"),
                    'password' => md5($form->getValue("password")),
                    'fullname' => $form->getValue("fullname"),
                    'email'    => $form->getValue("email"),
                    'phone'    => $form->getValue("phone"),
                    'address'  => $form->getValue("address"),
                    'country'  => $form->getValue("country"),
                    'role'     => $form->getValue("role"),
                    'created_date' => time()
                );
                $user_db = new Core_Model_DbTable_Users();
                try {
                    $user_db->insert($data);
                    $this->_helper->redirector("users");
                } catch (Exception $e) {
                    $errors = array (
                        'username' => array('Username has already existed')
                    );
                }
            } else {
                $errors = $form->getMessages();
            }
            if (!empty($errors)) {
                $this->view->countries = Core_Util::getCountryList();
                $this->view->roles = Core_Util::getRoleList();
                $this->view->user = (object)$form_data;
                $this->view->errors = $errors;
            }
        } else {
            $this->view->countries = Core_Util::getCountryList();
            $this->view->roles = Core_Role::getRoleList();
        }
    }
    
    public function edituserAction() {
        $this->view->mode = EDIT_MODE;
        $uid = $this->_getParam("uid");
        $need_redirect = false;
        if (!empty($uid)) {
            $user_db = new Core_Model_DbTable_Users();
            $user = $user_db->getDetail($uid);
            if (!empty($user)) {
                if ($this->getRequest()->isPost()) {
                    $form = new Admin_Form_Newuser();
                    $form_data = $this->getRequest()->getPost();
                    $errors = array();
                    if ($form->isValid($form_data)) {
                        $data = array (
                            'username' => $form->getValue("username"),
                            'password' => md5($form->getValue("password")),
                            'fullname' => $form->getValue("fullname"),
                            'email'    => $form->getValue("email"),
                            'phone'    => $form->getValue("phone"),
                            'address'  => $form->getValue("address"),
                            'country'  => $form->getValue("country"),
                            'role'     => $form->getValue("role"),
                            'created_date' => time()
                        );
                        $user_db = new Core_Model_DbTable_Users();
                        try {
                            $user_db->update($data, $user_db->getAdapter()->quoteInto("id = (?)", $uid));
                            $this->_helper->redirector("users");
                        } catch (Exception $e) {
                            $errors = array (
                                'username' => array('Username has already existed')
                            );
                        }
                    } else {
                        $errors = $form->getMessages();
                    }
                    if (!empty($errors)) {
                        $this->view->errors = $errors;
                        $this->view->user = (object)$form_data;
                        $this->view->countries = Core_Util::getCountryList();
                        $this->view->roles = Core_Util::getRoleList();                    
                    }
                } else {
                    $this->view->user = $user;
                    $this->view->countries = Core_Util::getCountryList();
                    $this->view->roles = Core_Util::getRoleList();                    
                    $this->render("newuser");
                }
            } else {
                $need_redirect = true;
            }
        } else {
           $need_redirect = true;
        }
        if ($need_redirect) {
            $this->_helper->redirector("users");
        }
    }
    
    protected function _initMenuUrls() {
        $action = $this->getRequest()->getActionName();
        $active_menus = Core_Util::getAdminActiveMenu($action, $this->_getAllParams());
        $this->view->active_menu = $active_menus['active_menu'];
        $this->view->active_submenu = $active_menus['active_submenu'];
    }

    public function serviceAction(){
        $type = $this->_getParam("type");
        $is_save = $this->_getParam("saveContent");
        $services = Core_Util::getAllServices();
        $this->view->assign("current_service", $services[$type]);
        $file_folder = APPLICATION_PATH . DIRECTORY_SEPARATOR . "modules" .DIRECTORY_SEPARATOR . "Services" . DIRECTORY_SEPARATOR . "views" . DIRECTORY_SEPARATOR . "scripts" . DIRECTORY_SEPARATOR . "index" . DIRECTORY_SEPARATOR;
        $file_name =  $file_folder  . "{$type}.phtml";
        if(!file_exists($file_name)){
            chmod($file_folder,0777);
            mkdir($file_name);
        }
        chmod($file_name, 0777);

        if ($is_save == 1) {
            $content = $this->_getParam("content");
            file_put_contents($file_name, $content);
        }
        $content = file_get_contents($file_name);
        $this->view->assign("content", $content);
        $this->view->assign("current_type", $type);
    }

    public function aboutAction(){
        $is_save = $this->_getParam("saveContent");
        $file_folder = APPLICATION_PATH . DIRECTORY_SEPARATOR . "modules" .DIRECTORY_SEPARATOR . "Admin" . DIRECTORY_SEPARATOR . "views" . DIRECTORY_SEPARATOR . "scripts" . DIRECTORY_SEPARATOR . "index" . DIRECTORY_SEPARATOR;
        $file_name = $file_folder . 'about_content.phtml';
        $file_address = $file_folder . 'address_content.phtml';
        if(!file_exists($file_name)){
            chmod($file_folder, 0777);
            mkdir($file_name);
        }

        if(!file_exists($file_address)){
            chmod($file_folder, 0777);
            mkdir($file_address);
        }
        chmod($file_name, 0777);
        chmod($file_address, 0777);

        if($is_save == 1){
            $content = $this->_getParam("content");
            file_put_contents($file_name, $content);

            $content_address = $this->_getParam("content_address");
            file_put_contents($file_address, $content_address);
        }
        $content = file_get_contents($file_name);
        $content_address = file_get_contents($file_address);
        $this->view->assign("content", $content);
        $this->view->assign("content_address", $content_address);
    }

    public function emailsettingAction(){
        $config_db = new Core_Model_DbTable_Config();
        $saveContent = $this->_getParam("saveContent");
        if($saveContent == 1){
            $form = new Admin_Form_Newconfig();
            $form_data = $this->getRequest()->getPost();
            if($form->isValid($form_data)){
                $smtp_port = htmlspecialchars($form->getValue(SMTP_PORT));
                $smtp_host = htmlspecialchars($form->getValue(SMTP_HOST));
                $smtp_password = htmlspecialchars($form->getValue(SMTP_PASSWORD));
                $smtp_user = htmlspecialchars($form->getValue(SMTP_USER));
                $config_db->insertConfig(SMTP_HOST, $smtp_host);
                $config_db->insertConfig(SMTP_USER, $smtp_user);
                $config_db->insertConfig(SMTP_PASSWORD, $smtp_password);
                $config_db->insertConfig(SMTP_PORT, $smtp_port);
                $this->_helper->redirector('emailsetting');
            }else{
                $this->view->errors = $form->getMessages();
                $this->view->assign("smtp_host", $form->getValue(SMTP_HOST));
                $this->view->assign("smtp_port", $form->getValue(SMTP_PORT));
                $this->view->assign("smtp_user", $form->getValue(SMTP_USER));
                $this->view->assign("smtp_password", $form->getValue(SMTP_PASSWORD));
            }
        }else{
            $smtp_host = $config_db->getByKey(SMTP_HOST);
            $smtp_port = $config_db->getByKey(SMTP_PORT);
            $smtp_user = $config_db->getByKey(SMTP_USER);
            $smtp_password = $config_db->getByKey(SMTP_PASSWORD);
            $this->view->assign("smtp_host", $smtp_host["value"]);
            $this->view->assign("smtp_port", $smtp_port["value"]);
            $this->view->assign("smtp_user", $smtp_user["value"]);
            $this->view->assign("smtp_password", $smtp_password["value"]);
        }
    }

    public function materialAction(){
        $type = $this->_getParam("type", "dunnage");
        switch($type) {
            case "dunnage":
                $this->dunnagematerial();
                $view = "dunnagematerial";
                break;
            case "tally":
                $this->tallyservice();
                $view = "tallyservice";
                break;
        }
        $this->render($view);
    }

    public function dunnagematerial(){
        $dunnage = new Core_Model_DbTable_DunnageMaterials();
        if ($this->getRequest()->isPost()) {
            if(!is_null($this->_getParam("delete")) && $this->_getParam("delete") == 1)
            {
                $delete_ids = $this->_getParam("delete_ids");
                $dunnage->batchDelete($delete_ids);
            }
        }

        $search_name = $this->_getParam("search_name", '');
        $this->view->search_name = $search_name;
        $paginator_adapter = $dunnage->getPaginatorAdapter($search_name);
        $paginator = new Zend_Paginator($paginator_adapter);
        $page = $this->_getParam("page", 0);
        $paginator->setCurrentPageNumber($page);
        $this->view->units = Core_Util::getAllUnit();
        $this->view->paginator = $paginator;
        $this->view->action = "newdunnagematerial";
    }

    public function newdunnagematerialAction(){
        $this->view->mode = INSERT_MODE;
        $errors = array();
        if ($this->getRequest()->isPost()) {
            $form = new Admin_Form_Newdunnagematerial();
            $form_data = $this->getRequest()->getPost();
            if ($form->isValid($form_data)) {
                $data = array (
                    'type' => $form->getValue("type"),
                    'unit' => $form->getValue("unit"),
                    'price_per_unit' => $form->getValue("price_per_unit"),
                    'created_date' => time(),
                    'updated_date' => time()
                );
                $dunnage_tb = new Core_Model_DbTable_DunnageMaterials();
                $dunnage_tb->insert($data);
            } else {
                $errors = $form->getMessages();
            }
            if (!empty($errors)) {
                $this->view->type = $form_data['type'];
                $this->view->unit = $form_data['unit'];
                $this->view->price_per_unit = $form_data['price_per_unit'];
                $this->view->errors = $errors;
            }else{
                $this->_helper->redirector("material");
                return;
            }
        }
        $this->view->action = "newdunnagematerial";
        $this->view->units = Core_Util::getAllUnit();
    }

    public function editdunnagematerialAction() {
        $this->view->action = "editdunnagematerial";
        if($this->getRequest()->isPost()){
            $form = new Admin_Form_Newdunnagematerial();
            $form_data = $this->getRequest()->getPost();
            if ($form->isValid($form_data)) {
                if(is_null($form_data['id']) || empty ($form_data['id'])){
                    $errors['dunnagematerial'] = "Do not have material to update";
                }else{
                    $data = array (
                        'type' => $form->getValue("type"),
                        'unit' => $form->getValue("unit"),
                        'price_per_unit' => $form->getValue("price_per_unit"),
                        'updated_date' => time(),
                    );
                    $dunnage_tb = new Core_Model_DbTable_DunnageMaterials();
                    $dunnage_tb->update($data, $dunnage_tb->getAdapter()->quoteInto('`id` = (?)', $form_data['id']));
                }
            } else {
                $errors = $form->getMessages();
            }
            if (!empty($errors)) {
                $this->view->type = $form_data['type'];
                $this->view->unit = $form_data['unit'];
                $this->view->id   = $form_data['id'];
                $this->view->price_per_unit = $form_data['price_per_unit'];
                $this->view->errors = $errors;
            }else{
                $this->_helper->redirector("material");
                return;
            }
        }else{
            $id = $this->_getParam('uid');
            $dunnage_db = new Core_Model_DbTable_DunnageMaterials();
            $dunnage = $dunnage_db->getDetail($id);
            $this->view->type = $dunnage['type'];
            $this->view->unit = $dunnage['unit'];
            $this->view->id = $dunnage['id'];
            $this->view->price_per_unit = $dunnage['price_per_unit'];
        }
        $this->view->action = "editdunnagematerial";
        $this->view->units = Core_Util::getAllUnit();
        $this->render("newdunnagematerial");
    }

    public function tallyservice(){
        $tally = new Core_Model_DbTable_TallyServices();
        if ($this->getRequest()->isPost()) {
            if(!is_null($this->_getParam("delete")) && $this->_getParam("delete") == 1) {
                $delete_ids = $this->_getParam("delete_ids");
                $tally->batchDelete($delete_ids);
            }
        }

        $search_name = $this->_getParam("search_name", '');
        $this->view->search_name = $search_name;
        $paginator_adapter = $tally->getPaginatorAdapter($search_name);
        $paginator = new Zend_Paginator($paginator_adapter);
        $page = $this->_getParam("page", 0);
        $paginator->setCurrentPageNumber($page);
        $this->view->units = Core_Util::getAllUnit();
        $this->view->paginator = $paginator;
        $this->view->action = "newtallyservice";
    }

    public function newtallyserviceAction(){
        $this->view->mode = INSERT_MODE;
        $errors = array();
        if ($this->getRequest()->isPost()) {
            $form = new Admin_Form_Newtallyservice();
            $form_data = $this->getRequest()->getPost();
            if ($form->isValid($form_data)) {
                $data = array (
                    'service' => $form->getValue("service"),
                    'unit_price' => $form->getValue("unit_price"),
                );
                $tally_tb = new Core_Model_DbTable_TallyServices();
                $tally_tb->insert($data);
            } else {
                $errors = $form->getMessages();
            }
            if (!empty($errors)) {
                $this->view->service = $form_data['service'];
                $this->view->unit_price = $form_data['unit_price'];
                $this->view->errors = $errors;
            } else {
                $this->_helper->redirector->gotoUrl("/admin/index/material/type/tally");
                return;
            }
        }
        $this->view->action = "newtallyservice";
    }

    public function edittallyserviceAction() {
        if($this->getRequest()->isPost()){
            $form = new Admin_Form_Newtallyservice();
            $form_data = $this->getRequest()->getPost();
            $id_service = $this->_getParam("id");
            if ($form->isValid($form_data)) {
                if(is_null($id_service) || empty($id_service)){
                    $errors['tallyservice'] = "Do not have service to update";
                }else{
                    $data = array (
                        'service' => $form->getValue("service"),
                        'unit_price' => $form->getValue("unit_price"),
                    );
                    $tally_db = new Core_Model_DbTable_TallyServices();
                    $tally_db->update($data, $tally_db->getAdapter()->quoteInto('`id` = (?)', $this->_getParam('id')));
                }
            } else {
                $errors = $form->getMessages();
            }

            if (!empty($errors)) {
                $this->view->service = $form_data['service'];
                $this->view->unit_price = $form_data['unit_price'];
                $this->view->id   = $form_data['id'];
                $this->view->errors = $errors;
            }else{
                $this->_helper->redirector->gotoUrl("/admin/index/material/type/tally");
                return;
            }
        }else{
            $id = $this->_getParam('uid');
            $tally_db = new Core_Model_DbTable_TallyServices();
            $tally = $tally_db->getDetail($id);
            $this->view->service = $tally['service'];
            $this->view->unit_price = $tally['unit_price'];
            $this->view->id = $tally['id'];
        }
        $this->view->action = "edittallyservice";
        $this->render("newtallyservice");
    }
}

?>
